Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

String basics

Numbers in String

In Java, numbers can be represented as String objects. This is often useful when you need to perform operations such as concatenation with other strings or when you need to manipulate the number as text. Here’s how you can create a String from a number:
toString()-javaint num = 123; String str = Integer.toString(num);
In this case, str would be the string "123". You can also use the String.valueOf() method, which works with all types of numbers, not just int:
String.valueOf()double num = 123.45; String str = String.valueOf(num);
In this case, str would be the string "123.45". If you have a String that represents a number and you want to convert it back to a number, you can use the parseInt() or parseDouble() methods from the Integer and Double classes respectively:
parseInt()String str = "123"; int num = Integer.parseInt(str);
In this case, num would be the integer 123.
parseDouble()String str = "123.45"; double num = Double.parseDouble(str);
In this case, num would be the double 123.45. Remember, these parse methods will throw a NumberFormatException if the string cannot be parsed to a number. You should use a try-catch block to handle this exception if you’re not sure whether the string can be parsed to a number.
try-catchString str = "123abc"; try { int num = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println(str + " cannot be converted to int"); }
In this case, the catch block would be executed and "123abc cannot be converted to int" would be printed to the console. Understanding how to work with numbers and strings is a fundamental skill in Java, as it allows for greater flexibility in how you can use and manipulate data. It’s especially important when dealing with user input, as this often comes in the form of strings. By knowing how to convert between numbers and strings, you can ensure that your programs are robust and flexible.

  📌TAGS

★String ★java ★string methods ★ string literals ★ string escape sequence ★ number in string

Tutorials